#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from project.flasky import db
from project.define import db_logger


DataName = "车位"
TableName = "app_carpark_place"


class CarParkPlace(db.Model):
    """
    车位信息
    """
    __tablename__ = TableName
    # 车位ID
    PlaceID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 车型：Car,Moto
    VehicleType = db.Column(db.String(32), nullable=False)
    # 通过模式: Monthly, Hourly, Private
    ParkingType = db.Column(db.String(16), nullable=False)
    # 通过方式: LicensePlate, Card, Ticket
    ParkingMethods = db.Column(db.String(32), nullable=False)
    # 车位数量
    Provide = db.Column(db.Integer, nullable=False)
    # 保留车位
    Retain = db.Column(db.Integer)
    # 在场数量
    Parking = db.Column(db.Integer)
    # 剩余数量
    ValidCount = db.Column(db.Integer)

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.VehicleType = kwargs.get('VehicleType')
        self.ParkingType = kwargs.get('ParkingType')
        self.ParkingMethods = self.__methods_string(kwargs.get('ParkingMethods'))
        self.Provide = kwargs.get('Provide')
        self.Retain = kwargs.get('Retain')

    def __methods_string(self, val):
        """
        数据转换
        """
        if isinstance(val, list):
            if len(val) == 1:
                return val[0]
            else:
                return ",".join(val)

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(name):
            val = getattr(self, name)
            if name == "ParkingMethods":
                if "," in val:
                    val = val.split(",")
                else:
                    val = [val,]
            return val

        return dict([(c.name, convert_data(c.name)) for c in self.__table__.columns])

    def parking_methods_name(self, **kwargs):
        """
        停车方式
        """
        if "," in self.ParkingMethods:
            parking_methods = self.ParkingMethods.split(",")
        else:
            parking_methods = [self.ParkingMethods]
        methods = [kwargs.get(i) for i in parking_methods]
        if len(methods) > 1:
            return ",".join(methods)
        elif len(methods) == 1:
            return methods[0]

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'PlaceID':'車位ID','VehicleType':'車輛類型','ParkingType': '車位類型', 'ParkingMethods':'停車方式','Provide': '提供數量','Retain':'保留車位'}
        return ColumnName
    
    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        place_id = kwargs.get('PlaceID')
        if place_id:
            return CarParkPlace.query.filter_by(PlaceID=place_id).first()

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(CarParkPlace, k):
                    if k == 'VehicleType':
                        filters.add(CarParkPlace.VehicleType == v)
                    elif k == 'ParkingType':
                        filters.add(CarParkPlace.ParkingType == v)
                    elif k == 'ParkingMethods':
                        for i in v:
                            filters.add(CarParkPlace.ParkingMethods.like(f"%{i}%"))
        return filters

    @staticmethod
    def place_exists(**kwargs):
        """
        车位存在
        """
        vehicle_type = kwargs.get("VehicleType")
        parking_type = kwargs.get("ParkingType")
        return CarParkPlace.query.filter_by(VehicleType=vehicle_type,ParkingType=parking_type).first()

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = CarParkPlace(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = CarParkPlace.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}D成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            update = False
            r = CarParkPlace.selected_data(**kwargs)
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if k == "ParkingMethods":
                            v = ",".join(v)
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")

    @staticmethod
    def table_init():
        """
        初始化
        """
        demo_data = [
            {'VehicleType':'Car','ParkingType': 'Hourly', 'ParkingMethods':['LicensePlate','Ticket'],'Provide': 10,'Retain':0},
            {'VehicleType':'Moto','ParkingType': 'Hourly', 'ParkingMethods':['LicensePlate','Ticket'],'Provide': 10,'Retain':0},
            {'VehicleType':'Car','ParkingType': 'Monthly', 'ParkingMethods':['LicensePlate','Card'],'Provide': 10,'Retain':0},
            {'VehicleType':'Moto','ParkingType': 'Monthly', 'ParkingMethods':['LicensePlate','Card'],'Provide': 10,'Retain':0},
            {'VehicleType':'Car','ParkingType': 'Private', 'ParkingMethods':['LicensePlate','Card'],'Provide': 5,'Retain':0},
            {'VehicleType':'Moto','ParkingType': 'Private', 'ParkingMethods':['LicensePlate','Card'],'Provide': 2,'Retain':0},
        ]
        for i in demo_data:
            vehicle_type = i.get("VehicleType")
            parking_type = i.get("ParkingType")
            r = CarParkPlace.query.filter_by(VehicleType=vehicle_type,ParkingType=parking_type).first()
            if not r:
                r = CarParkPlace.insert_data(**i)